<template>
  <div>
    <!-- Breadcrumb Navigation area -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">Home</el-breadcrumb-item>
      <el-breadcrumb-item>Goods</el-breadcrumb-item>
      <el-breadcrumb-item>Add</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- card view area -->
    <el-card>
      <!-- some info add goods -->
      <el-alert title="Add Goods info" type="info" show-icon :closable="false" effect="dark" center></el-alert>

      <!-- goods add steps  -->
      <el-steps :space="200" :active="activeIndex" finish-status="success" align-center>
        <el-step title="Basic Information"></el-step>
        <el-step title="Goods Params"></el-step>
        <el-step title="Goods Attrs"></el-step>
        <el-step title="Goods image"></el-step>
        <el-step title="Goods Content"></el-step>
        <el-step title="Finish"></el-step>
      </el-steps>

      <!-- Add Goods Form -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- Right Tabs -->
        <el-tabs tab-position="right" v-model="activeName" :before-leave="beforeTabLeave">
          <el-tab-pane label="Basic Information" name="0">
            <el-form-item label="Goods Name" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="Goods Price" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="Goods Weight" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="Nr Of Goods" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="Goods Category" prop="goods_cat">
              <!-- Cascader of goods category -->
              <el-cascader
                :options="cateList"
                :props="cateCascaderProps"
                v-model="addForm.goods_cat"
                @change="cateSelectedChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="Goods Params" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in dynicParamList"
              :key="item.attr_id"
            >
              <!-- Checkbox group -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="val" v-for="(val, idx) in item.attr_vals" :key="idx"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="Goods Attrs" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in staticAttrList"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="Goods image" name="3">
            <!-- Upload image -->
            <!-- action: Where are the file uploaded? -->
            <el-upload
              :action="uploadURL"
              :on-preview="imagePreview"
              :on-remove="imageRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="imageUploaded"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="Goods Content" name="4">
            <!-- Rich text editor -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="btnAdd" @click="addGoods">Add Godds</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- image preview dialog -->
    <el-dialog title="Image Preview" :visible.sync="imagePreviewDialogVisible" width="47%">
      <img :src="imagePreviewURL" class="imagePreview" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getCateList()
  },
  data() {
    return {
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      activeName: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [1, 3, 6],
        pics: [],
        /* Goods desc */
        goods_introduce: '',
        attrs: []
      },
      addFormRules: {
        goods_name: [
          {
            required: true,
            message: 'Plese enter a goods name',
            trigger: 'blur'
          }
        ],
        goods_price: [
          {
            required: true,
            message: 'Plese enter a goods price',
            trigger: 'blur'
          }
        ],
        goods_weight: [
          {
            required: true,
            message: 'Plese enter a goods weight',
            trigger: 'blur'
          }
        ],
        goods_number: [
          {
            required: true,
            message: 'Plese enter a nr of goods',
            trigger: 'blur'
          }
        ],
        goods_cat: [
          {
            required: true,
            message: 'Plese choose a goods category',
            trigger: 'blur'
          }
        ]
      },
      cateList: [],
      /* cascader config object */
      cateCascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      dynicParamList: [],
      staticAttrList: [],
      imagePreviewURL: '',
      imagePreviewDialogVisible: false
    }
  },
  computed: {
    activeIndex() {
      return parseInt(this.activeName)
    },
    selectedCateId() {
      return this.addForm.goods_cat.length === 3 ? this.addForm.goods_cat[2] : null
    }
  },
  methods: {
    async getCateList() {
      const rs = await this.$http.get('categories')
      if (rs.meta.status !== 200) {
        return this.$msg.error('get category list faild!')
      }
      this.cateList = rs.data
      // console.log(this.cateList);
    },
    cateSelectedChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
      // console.log(this.addForm.goods_cat);
    },
    beforeTabLeave(to, form) {
      if (to - form > 1) {
        this.$msg.info('Please setup by setup!')
        return false
      }
      /* not choose a category */
      if (form === '0' && this.addForm.goods_cat.length !== 3) {
        this.$msg.info('Please choose a category!')
        return false
      }
      /* Get data in advance */
      switch (to - 0) {
        case 1:
          this.getDynicParamList()
          break
        case 2:
          this.getStaticAttrList()
          break
      }
      return true
    },
    async getDynicParamList() {
      const rs = await this.$http.get(`categories/${this.selectedCateId}/attributes`, {
        params: { sel: 'many' }
      })
      if (rs.meta.status !== 200) {
        return this.$msg.error('get dynic param list faild!')
      }
      rs.data.forEach(item => {
        item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
      })
      this.dynicParamList = rs.data
      // console.log(this.dynicParamList)
    },
    async getStaticAttrList() {
      const rs = await this.$http.get(`categories/${this.selectedCateId}/attributes`, {
        params: { sel: 'only' }
      })
      if (rs.meta.status !== 200) {
        return this.$msg.error('get static attr list faild!')
      }
      this.staticAttrList = rs.data
      // console.log(this.staticAttrList)
    },
    imagePreview(file) {
      this.imagePreviewURL = file.response.data.url
      this.imagePreviewDialogVisible = true
    },
    imageRemove(file) {
      // console.log(file)
      /* get file tmp path */
      const tmpPath = file.response.data.tmp_path
      /* find file index from pics array  */
      const idx = this.addForm.pics.findIndex(item => {
        return item.pic === tmpPath
      })
      /* remove from pics array */
      this.addForm.pics.splice(idx, 1)
      // console.log(this.addForm)
    },
    imageUploaded(rep, req) {
      /* splice image info */
      const picInfo = { pic: rep.data.tmp_path }
      /* push image info to pics */
      this.addForm.pics.push(picInfo)
      // console.log(this.addForm)
    },
    addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$msg.error('Plese fill required form item!')
        }
        /* loadsh   cloneDeep() */
        const clone = JSON.parse(JSON.stringify(this.addForm))
        clone.goods_cat = clone.goods_cat.join(',')
        this.dynicParamList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals.join()
          }
          this.addForm.attrs.push(newInfo)
        })
        this.staticAttrList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        })
        clone.attrs = this.addForm.attrs
        // console.log(clone)
        const rs = await this.$http.post('goods', clone)
        if (rs.meta.status !== 201) {
          return this.$msg.error('Add goods faild!')
        }
        this.$msg.success('Add goods success!')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 9px 0 0 !important;
}
.imagePreview {
  width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
</style>
